package avicit.bdp.lineage.druid.process.statement;

import avicit.bdp.lineage.druid.anotation.SQLObjectType;
import avicit.bdp.lineage.druid.contants.ParserConstant;
import avicit.bdp.lineage.druid.model.TableNode;
import avicit.bdp.lineage.druid.model.TreeNode;
import avicit.bdp.lineage.druid.process.ProcessorRegister;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.statement.SQLCreateTableStatement;
import com.alibaba.druid.sql.ast.statement.SQLExprTableSource;
import com.alibaba.druid.sql.ast.statement.SQLInsertStatement;
import com.alibaba.druid.sql.ast.statement.SQLSelectQuery;
import com.alibaba.druid.sql.ast.statement.SQLWithSubqueryClause;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 * InsertStatement 处理
 * </p>
 */
@SQLObjectType(clazz = SQLCreateTableStatement.class)
public class SQLCreateTableStatementProcessor extends AbstractStatementProcessor {

    @Override
    public void doProcess(String dbType, AtomicInteger sequence, TreeNode<TableNode> root, SQLStatement statement) {
        SQLCreateTableStatement sqlCreateTableStatement = (SQLCreateTableStatement) statement;
        SQLExprTableSource sqlExprTableSource = sqlCreateTableStatement.getTableSource();
        // 构建根表
        this.constructRootNode(dbType, root, statement, sqlExprTableSource);
        //构建根表字段
//        List<SQLExpr> exprList = sqlCreateTableStatement.getColumns();
//        if (Objects.nonNull(exprList)) {
//            this.constructRootNodeField(dbType, root, statement, exprList);
//        }

        // 获取SQLSelectQuery
        SQLSelectQuery sqlSelectQuery = sqlCreateTableStatement.getSelect().getQuery();
        // 执行SQLSelectQuery 查询
        ProcessorRegister.getSQLSelectQueryProcessor(sqlSelectQuery.getClass())
                .process(dbType, sequence, root, sqlSelectQuery);

        // 构建with字段
        SQLWithSubqueryClause subqueryClause = sqlCreateTableStatement.getSelect().getWithSubQuery();
        if (subqueryClause != null) {
            processWithSQL(dbType, sequence, root, subqueryClause);
        }
    }

}
